<?php

require_once dirname(__FILE__).'/../lib/vgBusinessCategoryGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/vgBusinessCategoryGeneratorHelper.class.php';

/**
 * vgMember actions.
 *
 * @package    BDS
 * @subpackage vgMember
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class vgBusinessCategoryActions extends autoVgBusinessCategoryActions
{
    public function executeListActive(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $q = Doctrine_Query::create()->update('vgBusinessCategory bc')->set('bc.is_active', 1)->where('id=?', $id);
        Doctrine_Core::getTable('vgBusinessCategory')->activeList($q);
        $this->redirect('@vg_business_category');
    }

    public function executeListDeactive(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $q = Doctrine_Query::create()->update('vgBusinessCategory bc')->set('bc.is_active', 0)->where('id=?', $id);
        Doctrine_Core::getTable('vgBusinessCategory')->deactiveList($q);
        $this->redirect('@vg_business_category');
    }
    public function executeBatchActive(sfWebRequest $request) {

        $ids = $request->getParameter('ids');
        $q = Doctrine_Query::create()->update('vgBusinessCategory bc')->set('bc.is_active', 1)->whereIn('id', $ids);
        Doctrine_Core::getTable('vgBusinessCategory')->active($q);

        //$this->redirect('@vg_business_category');
    }
    public function executeBatchDeactive(sfWebRequest $request) {
        $ids = $request->getParameter('ids');
        $q = Doctrine_Query::create()->update('vgBusinessCategory bc')->set('bc.is_active', 0)->whereIn('id', $ids);
        Doctrine_Core::getTable('vgBusinessCategory')->deactive($q);

        //$this->redirect('@vg_business_category');
    }
    public function preExecute()
    {
        $this->configuration = new vgBusinessCategoryGeneratorConfiguration();

        if (!$this->getUser()->hasCredential($this->configuration->getCredentials($this->getActionName())))
        {
            $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
        }

        $this->dispatcher->notify(new sfEvent($this, 'admin.pre_execute', array('configuration' => $this->configuration)));

        $this->helper = new vgBusinessCategoryGeneratorHelper();

        parent::preExecute();
    }

    public function executeAjax(sfWebRequest $request)
    {
        $class_name = sfInflector::camelize($request->getParameter('model'));
        $id = $request->getParameter('row_id');

        if (class_exists($class_name))
        {
            $method = sfInflector::camelize($request->getParameter('field_name'));
            $method_set = 'set' . $method;
            $method_get = 'get' . $method;

            $record = Doctrine::getTable("{$class_name}")->findOneBy('id', $id);

            if ($record)
            {
                $record->$method_set($request->getParameter('value'));
                $record->save();
            }
        }

        return $this->renderText($record->$method_get());
    }

    public function executeIndex(sfWebRequest $request)
    {
        // sorting
        if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort')))
        {
            $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));
        }

        // pager
        if ($request->getParameter('page'))
        {
            $this->setPage($request->getParameter('page'));
        }

        // max per page
        if ($request->getParameter('max_per_page'))
        {
            $this->setMaxPerPage($request->getParameter('max_per_page'));
        }

        $this->sidebar_status = $this->configuration->getListSidebarStatus();

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();

        if (count($this->getUser()->getAttribute('vgBusinessCategory.filters', array(), 'admin_module')) > 0)
        {
            //$this->getUser()->setFlash('notice', 'Có sử dụng bộ lọc , các kết quả có thể không được hiển thị toàn bộ.');
        }
    }

    public function executeFilter(sfWebRequest $request)
    {
        $this->setPage(1);

        if ($request->hasParameter('_reset'))
        {
            $this->setFilters($this->configuration->getFilterDefaults());

            $this->redirect('@vg_business_category');
        }

        $this->filters = $this->configuration->getFilterForm($this->getFilters());

        $this->filters->bind($request->getParameter($this->filters->getName()));
        if ($this->filters->isValid())
        {
            $this->setFilters($this->filters->getValues());

            $this->redirect('@vg_business_category');
        }

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();

        $this->setTemplate('index');
    }

    public function executeNew(sfWebRequest $request)
    {
        $this->sidebar_status = $this->configuration->getNewSidebarStatus();
        $this->form = $this->configuration->getForm();
        $this->vg_business_category = $this->form->getObject();
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->sidebar_status = $this->configuration->getNewSidebarStatus();
        $this->form = $this->configuration->getForm();
        $this->vg_business_category = $this->form->getObject();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request)
    {
        $this->sidebar_status = $this->configuration->getEditSidebarStatus();
        $this->vg_business_category = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->vg_business_category);
        $this->fields = $this->vg_business_category->getTable()->getColumnNames();
    }

    public function executeShow(sfWebRequest $request)
    {
        $this->sidebar_status = $this->configuration->getShowSidebarStatus();
        $hide = array();
        $this->vg_business_category = $this->getRoute()->getObject();
        $this->fields = array_diff($this->vg_business_category->getTable()->getColumnNames(), $hide);
    }

    public function executeRevert(sfWebRequest $request)
    {
        $object = $this->getRoute()->getObject();
        $to_version = $request->getParameter('version');

        try
        {
            $object->revert($to_version);
            $object->save();
            $this->getUser()->setFlash('notice', 'Item was reverted to version #' . $to_version);
        }
        catch (Exception $exc)
        {
            $this->getUser()->setFlash('error', 'Could not revert item to desired version.', false);
        }

        $redirect = $request->getReferer() ? $request->getReferer() : array('sf_route' => 'vg_business_category_show', 'sf_subject' => $object);

        $this->redirect($redirect);

    }
    public function executeUpdate(sfWebRequest $request)
    {
        $this->sidebar_status = $this->configuration->getEditSidebarStatus();
        $this->vg_business_category = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->vg_business_category);
        $this->fields = $this->vg_business_category->getTable()->getColumnNames();

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request)
    {
        $request->checkCSRFProtection();

        $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->getRoute()->getObject())));

        if ($this->getRoute()->getObject()->delete())
        {
            $this->getUser()->setFlash('notice', 'Bản ghi đã được xóa thành công');
        }

        $this->redirect('@vg_business_category');
    }

    public function executeBatch(sfWebRequest $request)
    {
        $request->checkCSRFProtection();

        if (!$ids = $request->getParameter('ids'))
        {
            $this->getUser()->setFlash('error', 'Bạn phải chọn ít nhất 1 bản ghi');

            $this->redirect('@vg_business_category');
        }

        if (!$action = $request->getParameter('batch_action'))
        {
            $this->getUser()->setFlash('error', 'Bạn phải chọn hành động để thực thi bản ghi đã chọn');

            $this->redirect('@vg_business_category');
        }

        if (!method_exists($this, $method = 'execute'.ucfirst($action)))
        {
            throw new InvalidArgumentException(sprintf('You must create a "%s" method for action "%s"', $method, $action));
        }

        if (!$this->getUser()->hasCredential($this->configuration->getCredentials($action)))
        {
            $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
        }

        $validator = new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'vgBusinessCategory'));
        try
        {
            // validate ids
            $ids = $validator->clean($ids);

            // execute batch
            $this->$method($request);
        }
        catch (sfValidatorError $e)
        {
            $this->getUser()->setFlash('error', 'A problem occurs when deleting the selected items as some items do not exist anymore.');
        }

        $this->redirect('@vg_business_category');
    }

    protected function executeBatchDelete(sfWebRequest $request)
    {
        $ids = $request->getParameter('ids');

        $records = Doctrine_Query::create()
            ->from('vgBusinessCategory')
            ->whereIn('id', $ids)
            ->execute();

        foreach ($records as $record)
        {
            $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $record)));

            $record->delete();
        }

        $this->getUser()->setFlash('notice', 'Đã xóa thành công bản ghi được chọn.');
        $this->redirect('@vg_business_category');
    }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            $notice = $form->getObject()->isNew() ? 'Bản ghi mới đã được tạo thành công.' : 'Bản ghi mới đã được sửa thành công.';

            try {
                $vg_business_category = $form->save();
            } catch (Doctrine_Validator_Exception $e) {

                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors) {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('form' => $form, 'object' => $vg_business_category)));

            if ($request->hasParameter('_save_and_add'))
            {
                $this->getUser()->setFlash('success', $notice.' Bạn có thể thêm bản ghi mới.');

                $this->redirect('@vg_business_category_new');
            }
            else
            {
                $this->getUser()->setFlash('success', $notice);

                //$this->redirect(array('sf_route' => 'vg_business_category_show', 'sf_subject' => $vg_business_category));
            }
        }
        else
        {
            $this->getUser()->setFlash('error', 'Xảy ra lỗi , vui lòng thử lại.', false);
        }
    }

    protected function getFilters()
    {
        return $this->getUser()->getAttribute('vgBusinessCategory.filters', $this->configuration->getFilterDefaults(), 'admin_module');
    }

    protected function setFilters(array $filters)
    {
        return $this->getUser()->setAttribute('vgBusinessCategory.filters', $filters, 'admin_module');
    }

    protected function getPager()
    {
        $pager = $this->configuration->getPager('vgBusinessCategory');
        $pager->setQuery($this->buildQuery());
        $pager->setPage($this->getPage());
        $pager->init();

        return $pager;
    }

    protected function setMaxPerPage($max_per_page)
    {
        $this->getUser()->setAttribute('vgBusinessCategory.max_per_page', (integer) $max_per_page, 'admin_module');
    }

    protected function setPage($page)
    {
        $this->getUser()->setAttribute('vgBusinessCategory.page', $page, 'admin_module');
    }

    protected function getPage()
    {
        return $this->getUser()->getAttribute('vgBusinessCategory.page', 1, 'admin_module');
    }

    protected function buildQuery()
    {
        $tableMethod = $this->configuration->getTableMethod();
        if (null === $this->filters)
        {
            $this->filters = $this->configuration->getFilterForm($this->getFilters());
        }

        $this->filters->setTableMethod($tableMethod);

        $query = $this->filters->buildQuery($this->getFilters());

        $this->addSortQuery($query);

        $event = $this->dispatcher->filter(new sfEvent($this, 'admin.build_query'), $query);
        $query = $event->getReturnValue();

        return $query;
    }

    protected function addSortQuery($query)
    {
        if (array(null, null) == ($sort = $this->getSort()))
        {
            return;
        }

        if (!in_array(strtolower($sort[1]), array('asc', 'desc')))
        {
            $sort[1] = 'asc';
        }

        $query->addOrderBy($sort[0] . ' ' . $sort[1]);
    }

    protected function getSort()
    {
        if (null !== $sort = $this->getUser()->getAttribute('vgBusinessCategory.sort', null, 'admin_module'))
        {
            return $sort;
        }

        $this->setSort($this->configuration->getDefaultSort());

        return $this->getUser()->getAttribute('vgBusinessCategory.sort', null, 'admin_module');
    }

    protected function setSort(array $sort)
    {
        if (null !== $sort[0] && null === $sort[1])
        {
            $sort[1] = 'asc';
        }

        $this->getUser()->setAttribute('vgBusinessCategory.sort', $sort, 'admin_module');
    }

    protected function isValidSortColumn($column)
    {
        return Doctrine_Core::getTable('vgBusinessCategory')->hasColumn($column);
    }

    public function executePromote(sfWebRequest $request)
    {
        $object = $this->getRoute()->getObject();
        $this->forward404Unless($object);
        $object->promote();

        $this->getUser()->setFlash('notice', 'Object promoted.');

        $this->redirect($this->helper->getUrlForAction('list'));
    }

    public function executeDemote(sfWebRequest $request)
    {
        $object = $this->getRoute()->getObject();
        $this->forward404Unless($object);
        $object->demote();

        $this->getUser()->setFlash('notice', 'Object demoted.');
        $this->redirect($this->helper->getUrlForAction('list'));
    }

    public function executeMove(sfWebRequest $request)
    {
        $object = $this->getRoute()->getObject();
        $this->forward404Unless($object);

        $position = (integer) $this->getRequestParameter('position', 0);
        if ($position > 0)
        {
            $object->moveToPosition($position);
            $this->getUser()->setFlash('notice', 'Object has been moved successfully to new position.');
        }
        else
        {
            $this->getUser()->setFlash('error', 'Invalid position.');
        }
        $this->redirect($this->helper->getUrlForAction('list'));
    }
}
